﻿/******************************************************************************
* SunnyUI.FrameDecoder 开源TCP、串口数据解码库。
* CopyRight (C) 2022-2023 ShenYongHua(沈永华).
* QQ群：56829229 QQ：17612584 EMail：SunnyUI@qq.com
*
* Blog:   https://www.cnblogs.com/yhuse
* Gitee:  https://gitee.com/yhuse/SunnyUI.FrameDecoder
*
* SunnyUI.FrameDecoder.dll can be used for free under the MIT license.
* If you use this code, please keep this note.
* 如果您使用此代码，请保留此说明。
******************************************************************************
* 文件名称: DataPool.cs
* 文件说明: 数组数据池
* 当前版本: V4.0
* 创建日期: 2023-01-28
*
* 2023-01-28: V4.0.0 增加文件说明
******************************************************************************/

using System;
using System.Buffers;

namespace Sunny.FrameDecoder
{
    /// <summary>
    /// 数组数据池
    /// </summary>
    internal static class DataPool<T>
    {
        /// <summary>
        /// 数据池单例
        /// </summary>
        /// <returns>数据池</returns>
        private static ArrayPool<T> Shared()
        {
            if (arrayPool == null)
            {
                arrayPool = ArrayPool<T>.Create();
            }

            return arrayPool;
        }

        private static ArrayPool<T> arrayPool;

        /// <summary>
        /// 租借字节数组
        /// </summary>
        /// <param name="minimumLength"></param>
        /// <returns></returns>
        public static T[] Rent(int minimumLength)
        {
            T[] array = Shared().Rent(minimumLength);
            array.AsSpan().Clear();
            return array;
        }

        /// <summary>
        /// 归还字节数组
        /// </summary>
        /// <param name="array"></param>
        /// <param name="clearArray"></param>
        public static void Return(T[] array, bool clearArray = true)
        {
            Shared().Return(array, clearArray);
        }
    }
}
